package com.zwb.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwb.service.dto.MenusRoleDto;
import com.zwb.service.mapper.MenuRoleMapper;
import com.zwb.service.pojo.MenuRole;
import com.zwb.service.service.IMenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zwb
 * @since 2022-08-23
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    @Autowired(required = false)
    private MenuRoleMapper menuRoleMapper;

    /**
     * 更新角色信息
     *
     * @param menusRoleDto
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateMenusRole(MenusRoleDto menusRoleDto) {

        List<Integer> sourceList = menuRoleMapper.selectList(
                new LambdaQueryWrapper<MenuRole>().eq(MenuRole::getRid, menusRoleDto.getRoleId())
        ).stream().map(MenuRole::getMid).collect(Collectors.toList());

        // 需要添加的数据
        ArrayList<Integer> addList = new ArrayList<>(Arrays.asList(new Integer[menusRoleDto.getMenusId().size()]));
        Collections.copy(addList, menusRoleDto.getMenusId());
        addList.removeAll(sourceList);

        // 需要删除的数据
        ArrayList<Integer> delList = new ArrayList<>(Arrays.asList(new Integer[sourceList.size()]));
        Collections.copy(delList, sourceList);
        delList.removeAll(menusRoleDto.getMenusId());

        Integer roleId = menusRoleDto.getRoleId();
        // 添加数据
        if (!ObjectUtils.isEmpty(addList)) {
            ArrayList<MenuRole> menuRoles = new ArrayList<>();
            for (Integer integer : addList) {
                MenuRole menuRole = new MenuRole();
                menuRole.setMid(integer);
                menuRole.setRid(roleId);
                menuRoles.add(menuRole);
            }
            this.saveBatch(menuRoles);
        }
        // 删除数据
        if (!ObjectUtils.isEmpty(delList)) {
            LambdaQueryWrapper<MenuRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MenuRole::getRid, roleId).in(MenuRole::getMid, delList);
            this.remove(queryWrapper);
        }

    }
}
